package com.yk.web.controller.system;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.yk.common.core.domain.entity.SysUser;
import com.yk.common.utils.WechatLoginUtil;
import com.yk.system.service.ISysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.yk.common.core.controller.BaseController;
import com.yk.common.core.domain.AjaxResult;
import com.yk.common.core.text.Convert;
import com.yk.common.utils.ServletUtils;
import com.yk.common.utils.StringUtils;
import com.yk.framework.web.service.ConfigService;
import com.yk.common.service.TokenService;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@Controller
public class SysLoginController extends BaseController
{
    /**
     * 是否开启记住我功能
     */
    @Value("${shiro.rememberMe.enabled: false}")
    private boolean rememberMe;

    @Autowired
    private ConfigService configService;
    @Autowired
    private ISysUserService sysUserService;

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, ModelMap mmap)
    {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request))
        {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        // 是否开启记住我
        mmap.put("isRemembered", rememberMe);
        // 是否开启用户注册
        mmap.put("isAllowRegister", Convert.toBool(configService.getKey("sys.account.registerUser"), false));
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe)
    {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            return success();
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @GetMapping("/unauth")
    public String unauth()
    {
        return "error/unauth";
    }

    /**
     * 小程序登录接口
     * @param code 小程序临时登录凭证
     * @return 登录结果
     */
    @Autowired
    private TokenService tokenService;

    @PostMapping("/miniProgramLogin")
    public String miniProgramLogin(@RequestBody Map<String, String> requestData) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 调用微信接口获取 openid 和 session_key
            String code = requestData.get("code");
            String encryptedData = requestData.get("encryptedData");
            String iv = requestData.get("iv");
            Map<String, String> wechatResult = WechatLoginUtil.getOpenIdAndSessionKey(code);
            String openId = wechatResult.get("openid");
            String sessionKey = wechatResult.get("session_key");
            String string = WechatLoginUtil.decryptPhoneNumber(encryptedData, sessionKey, iv);
            // 解密用户手机号
            JSONObject jsonObject = JSONObject.parseObject(string);

            // 取出 phoneNumber 键对应的值
            String phoneNumber = jsonObject.getString("phoneNumber");

            System.out.println(phoneNumber);
            // 根据 openId 查找或创建用户
            // 这里需要实现具体的用户查找或创建逻辑
             SysUser user = sysUserService.findOrCreateUserByOpenId(openId,phoneNumber);
//             if (user==null) {
//                 user.setOpenId(openId);
//                 user.setLoginName(phoneNumber);
//             }

            // 生成 token
            String token = tokenService.generateToken(openId);

            // 获取当前会话的 SESSIONID
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpSession session = request.getSession();
            String sessionId = session.getId();

            // 关联 SESSIONID 和用户数据权限
            // 这里需要实现具体的关联逻辑，例如将 SESSIONID 和用户 ID 存储到缓存中
            sysUserService.associateSessionIdWithUser(sessionId, user.getUserId());

            result.put("code", 200);
            result.put("message", "登录成功");
            result.put("token", token);
            result.put("sessionId", sessionId);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "登录失败：" + e.getMessage());
        }
        return "login";
    }
}
